import React, {PropTypes} from 'react';
import gql from 'graphql-tag';
import {connect} from 'react-apollo';
import {Link} from 'react-router';
import {Menu} from 'antd';
import Base from '../../base';
import _ from 'lodash';

const mapQueriesToProps = ({ownProps: props}) => ({
    data: {
        query: gql`
            query get($connection: String!, $database: String!) {
                tables(connection: $connection, database: $database) {
                    name
                }
            }
        `,
        variables: {
            connection: props.connection,
            database: props.database
        }
    }
});

@connect({mapQueriesToProps})
export default class Tables extends Base {
    static propTypes = {
        connection: PropTypes.string.isRequired,
        database: PropTypes.string.isRequired,
        setReload: PropTypes.func.isRequired
    };

    init() {
        this.data = 'tables';
    }

    mount() {
        this.props.setReload(this.props.data.refetch);
    }

    done(data) {
        const {connection, database} = this.props;
        const {conn, db, table} = this.context.params;
        const count = data.length.toString().length;
        const view = global.app.dbms.table.view;
        const key = `/dbms/${conn}/${db}/${table}/${view}`;
        return (
            <Menu defaultSelectedKeys={[key]}>
                {data.map(({name: table}, index) => {
                    const uri = `/dbms/${connection}/${database}/${table}/${view}`;
                    return (
                        <Menu.Item key={uri}>
                            <Link to={uri}>
                                <i className="fa fa-table fa-fw"/>
                                {_.padStart(++index, count, '0') + `. ${table}`}
                            </Link>
                        </Menu.Item>
                    );
                })}
            </Menu>
        );
    }
}
